﻿using System;
using System.Configuration;
using System.Net.Http.Extensions.Compression.Core.Compressors;
using System.Web.Http;
using System.Web.Http.ExceptionHandling;
using System.Web.Http.SelfHost;
using Common.Logging;
using In.Api.Pipeline.ExceptionHandlers;
using Microsoft.AspNet.WebApi.Extensions.Compression.Server;
using Newtonsoft.Json;

namespace In.Api
{
    class Program
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(Program));
        private static readonly string BaseAddress = ConfigurationManager.AppSettings["BaseAddress"];

        static void Main(string[] args)
        {
            HttpSelfHostServer server = null;
            try
            {
                // Set up server configuration
                var config = new HttpSelfHostConfiguration(BaseAddress);

                // Web API configuration and services
                // 打开错误调式信息输出到response
                // config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

                // 使用自定义TraceWriter，通过CommonLog记录下WebApi管道中的日志
                // config.Services.Replace(typeof(ITraceWriter), new CommonLogTraceWriter());

                // 使用默认TraceWrite
                // var traceWriter = config.EnableSystemDiagnosticsTracing();
                // traceWriter.IsVerbose = true;
                // traceWriter.MinimumLevel = TraceLevel.Debug;                

                // 添加 webapi 压缩处理，4096byte以下不压缩
                var serverCompressionHandler = new ServerCompressionHandler(4096, new GZipCompressor(),
                    new DeflateCompressor());
                config.MessageHandlers.Insert(0, serverCompressionHandler);

                // 全局Exception Logger 和 Handler
                // There can be multiple exception loggers. (By default, no exception loggers are registered.)
                config.Services.Add(typeof(IExceptionLogger), new CommonLogExceptionLogger());

                // There must be exactly one exception handler. (There is a default one that may be replaced.)
                // To make this sample easier to run in a browser, replace the default exception handler with one that sends
                // back text/plain content for all errors.
                config.Services.Replace(typeof(IExceptionHandler), new GenericExceptionHandler());

                // Attribute routing.
                config.MapHttpAttributeRoutes();

                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{action}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );

                // Create server
                server = new HttpSelfHostServer(config);

                // Start listening
                server.OpenAsync().Wait();
                Console.WriteLine("Listening on " + BaseAddress);
                Console.WriteLine("Hit [exit] to exit...");

                // Start Quartz Scheduler

                while (true)
                {
                    var key = Console.ReadLine();
                    if (key == "exit")
                    {
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                Logger.ErrorFormat("Open HttpSelfHost failed, info : {0}", JsonConvert.SerializeObject(e));

                Console.WriteLine("Could not start server: {0}", e.GetBaseException().Message);
                Console.WriteLine("Hit ENTER to exit...");
                Console.ReadLine();
            }
            finally
            {
                // Stop listening
                server?.CloseAsync().Wait();
            }
        }


    }
}
